<template>

	<div class="app-container" v-loading="data.mtloading">

		<div class="flex flex-wrap leading-10 mb-4" v-prmis="'machine_group_mg_getList'">
			<div class="language = 'en'?' ':'w-32’">{{ $t('machine.config') }}：</div>

			<div class="pl-8 w-3/12">
				<el-cascader :placeholder="$t('message.selectGroup')" style="width:100%" clearable :props="propss" v-model="data.groupValue" @change="getmping($event, 1)"
					@visible-change="onVisibleChange" />
			</div>

			<div class="pl-8 w-3/12">
				<el-select v-model="data.macping" :placeholder="$t('message.pleaseMachine')" clearable filterable
					@change="getmping($event, 2)">
					<el-option v-for="item in data.maclist" :key="item.value" :label="item.macid + '-' + item.label"
						:value="item.value" />
				</el-select>
			</div>

			<div class="w-full dashed mt-2 p-2" v-if="data.grouping.length != 0">
				<el-tag v-for="item, key of data.grouping" :key="key" closable :disable-transitions="false" class="mr-2"
					:type="item.mg_id == undefined ? '' : 'warning'" size="large" @close="handleClose(key)">
					{{ item.machine_id || item.value }}{{ item.mg_name || item.label || ' - ' + item.macid }}
				</el-tag>
			</div>

		</div>

		<div class="border border-[#4B8DF8]">
			<div class="bg-[#4B8DF8] text-[#fafafa] text-lg p-2 px-4 mb-4">{{ $t('machine.trade.switchConfig') }}</div>

			<div class="px-4">

				<div class="w-full flex flex-wrap h-10 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.switchApp') }}：</div>
					<div class="pl-8 w-3/12">
						<el-radio v-model="data.info.status" :label="1" border>{{ $t('public.open') }}</el-radio>
						<el-radio v-model="data.info.status" :label="2" border>{{ $t('public.close') }}</el-radio>
					</div>
				</div>

				<div class="w-full flex flex-wrap h-10 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.downAut') }}：</div>
					<div class="pl-8 w-3/12">
						<el-time-picker v-model="data.close_time" format="HH:mm" value-format="HH:mm" :clearable="false"
							style="width: 100%;" />
					</div>
				</div>

				<div class="w-full flex flex-wrap h-10 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.startAut') }}：</div>
					<div class="pl-8 w-3/12">
						<el-time-picker v-model="data.open_time" format="HH:mm" value-format="HH:mm" :clearable="false"
							style="width: 100%;" />
					</div>
				</div>

				<div class="w-full flex flex-wrap h-10 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.executionAut') }}：</div>
					<div class="pl-8 w-9/12">
						<el-tag v-for="item of data.week" @click="setweek(item.value)" type="warning" size="large"
							class="w-20 mr-6 cursor-pointer">{{ item.label }}</el-tag>
					</div>
				</div>

				<div class="w-full flex flex-wrap h-12 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.executionAutTime') }}：</div>
					<div class="pl-8 w-9/12 flex flex-wrap">
						<div v-for="item of data.week_time" class="w-20 mr-6 border text-center">
							<div class="h-6 leading-6" v-if="item.open != ''">{{ item.open || '' }}</div>
							<div class="h-6 leading-6" v-if="item.close != ''">{{ $t('machine.trade.sameDay') }}{{
								item.close || '' }}</div>
						</div>
					</div>
				</div>

			</div>
		</div>

		<div class="border border-[#FFB848] mt-8">
			<div class="bg-[#FFB848] text-[#fafafa] text-lg p-2 px-4 mb-4">{{ $t('machine.trade.businesConfig') }}</div>

			<div class="px-4">

				<div class="w-full flex flex-wrap h-10 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.automaticStop') }}：</div>
					<div class="pl-8 w-3/12">
						<el-time-picker v-model="data.cease_time" format="HH:mm" value-format="HH:mm" :clearable="false"
							style="width: 100%;" />
					</div>
				</div>

				<div class="w-full flex flex-wrap h-10 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.restore') }}：</div>
					<div class="pl-8 w-3/12">
						<el-time-picker v-model="data.restore_time" format="HH:mm" value-format="HH:mm"
							:clearable="false" style="width: 100%;" />
					</div>
				</div>

				<div class="w-full flex flex-wrap h-10 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.executionAut') }}：</div>
					<div class="pl-8 w-9/12">
						<el-tag v-for="item of data.week" @click="setmac(item.value)" type="warning" size="large"
							class="w-20 mr-6 cursor-pointer">{{ item.label }}</el-tag>
					</div>
				</div>

				<div class="w-full flex flex-wrap h-12 leading-10 mb-4">
					<div class="language = 'en'?' ':'w-32’">{{ $t('machine.trade.executionAut') }}：</div>
					<div class="pl-8 w-9/12 flex flex-wrap">
						<div v-for="item of data.mac_time" class="w-20 mr-6 border text-center">
							<div class="h-6 leading-6" v-if="item.open != ''">{{ item.open || '' }}</div>
							<div class="h-6 leading-6" v-if="item.close != ''">{{ $t('machine.trade.sameDay') }}{{
								item.close || '' }}</div>
						</div>
					</div>
				</div>

			</div>

		</div>

		<div class="w-1/2 text-left mt-6 ml-6">
			<div class="inline-block">
				<el-button type="primary" @click="submit" v-prmis="'machine_group_mg_getList'">{{
					$t('public.save') }}</el-button>
				<el-button @click="cancell">{{ $t('public.cancel') }}</el-button>
			</div>
		</div>


	</div>

</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import { getmachineList } from '@/api/machine';
import { getgroupList, getListgroupmg } from "@/api/machine_type";
import { addonoff } from '@/api/machine_trade';
import { useRouter } from "vue-router";
import { onMounted } from 'vue'
import { ElMessage } from 'element-plus'
let language = ref()
const { locale } = useI18n()
onMounted(() => {
	language.value = locale.value
})
let router = useRouter()

let data = reactive({
	groupValue: [],
	nodesData: [],
	mtloading: false, // 加载
	macgrouping: [], // 设备分组
	maclist: [], // 设备列表
	grouping: [], // 选中的设备
	bindmacping: [], // 设备分组绑定的设备
	week: [], // 执行周期
	mac_time: [], // 设备营业配置 - 自动执行时间
	week_time: [], // 开关机配置 - 自动执行时间
	info: { // 主体信息
		m_id: '',
		machine_id: '',
		machine_name: '',
		on_off_machine: '',
		on_off_ckc: '',
		status: 1
	},
	close_time: '22:00', // 自动关闭时间
	open_time: '07:00', // 自动开启时间
	cease_time: '22:00', // 自动停止营业时间
	restore_time: '07:00', // 恢复营业时间
	macping: '',// 选中的设备/分组
	num: 0, // 需要提交的次数
	sutnum: 0, // 已提交的次数
})
const propss = reactive(
	{
		checkStrictly: true,
		lazy: true,
		multiple: false,
		async lazyLoad(node: any, resolve: any) {
			const { level, value } = node
			let nodes = await getgroupList({ pid: value });
			if (nodes.state == 100 || nodes.state == 300) {
				resolve([]);
			}
			const nodesa = nodes.data.map((item) => ({
				value: item.mg_id,
				label: item.mg_id + '-' + item.mg_name
			}))
			nodes.data.forEach(item => {
				data.nodesData.push({
					value: item.mg_id,
					label: item.mg_id + '-' + item.mg_name
				})
			})
			resolve(nodesa);
		}
	}
)
// 加载数据
let setinfo = async () => {
	let week = [
		{ label: $t('mock.Monday'), value: '0' },
		{ label: $t('mock.Tuesday'), value: '1' },
		{ label: $t('mock.Wednesday'), value: '2' },
		{ label: $t('mock.Thursday'), value: '3' },
		{ label: $t('mock.Friday'), value: '4' },
		{ label: $t('mock.Saturday'), value: '5' },
		{ label: $t('mock.Sunday'), value: '6' },
	]
	data.week_time = []
	data.mac_time = []
	for (let i = 0; i <= 6; i++) {
		data.week_time.push({ value: '' + i + '', open: '', close: '' })
		data.mac_time.push({ value: '' + i + '', open: '', close: '' })
	}
	data.week = week

	// 设备列表
	if (data.maclist.length == 0) {
		await getmachineList({}).then(res => {
			if (res.state == 200) {
				for (let item of res.data) {
					data.maclist.push({
						label: item.machine_name,
						value: item.m_id,
						macid: item.machine_id
					})
				}
			}
		})
	}

	// 设备分组
	if (data.macgrouping.length == 0) {
		await getgroupList({}).then(res => {
			if (res.state == 200) {
				data.macgrouping = res.data
			}
		})
	}

	await getListgroupmg().then(res => {
		if (res.state == 200) {
			data.bindmacping = res.data
		}
	})

}
let onVisibleChange = () => {
	data.groupValue = []
}
// 选中分组/设备
let getmping = (e, k) => {
	let obj = ''
	let status = true
	if (k == 1) {
		// 分组
		data.nodesData.map((item) => {
			if (item.value === e[e.length - 1]) obj = item
		})
		for (let item of data.grouping) {
			if (item.value == obj.value) {
				status = false
			}
		}
	} else {
		// 设备
		data.maclist.map((item) => { if (item.value === e) obj = item })

		for (let item of data.grouping) {
			if (item.value == obj.value) {
				status = false
			}
		}
		data.macping = ''
	}
	if (status) {
		data.grouping.push(obj)
	}
}

// 删除选中的设备分组/设备
let handleClose = (e) => {
	data.grouping.splice(e, 1)
}

// 开关机配置 - 自动执行周期
let setweek = (e) => {
	data.week_time[e].open = data.close_time
	data.week_time[e].close = data.open_time
}

// 设备营业配置 - 自动执行周期
let setmac = (e) => {
	data.mac_time[e].open = data.cease_time
	data.mac_time[e].close = data.restore_time
}

// 保存
let submit = () => {
	let machine = []
	if (data.grouping.length == 0) {
		ElMessage({
			message: $t('message.pleaseSelectMachine'),
			type: 'error'
		})
		return
	}
	if (data.grouping.length != 0) {
		let grouping = []
		for (let item of data.grouping) {
		// 设备
			if (item.value != undefined) {
				data.maclist.map((ime) => {
					if (item.value === ime.value) {
						grouping.push(item.value)
					}
				})
			}

			if (item.m_id != undefined) {
				grouping.push(item.m_id)
			}
			// 设备分组
			if (item.value != undefined) {
				data.bindmacping.map((ime) => {
					if (item.value === ime.mg_id) {
						if(ime.m_id !== undefined){
							grouping.push(ime.m_id)
						}	
					}
				})
			}
		}
		// 设备分组放入指定设备中
		machine = [...machine, ...grouping]
	}

	// 去除重复的设备编号
	machine = [...new Set(machine)]

	let obj_machine = {}
	let obj_ckc = {}
	for (let item of data.week_time) {
		if (item.open != '' && item.close != '') {
			obj_machine[item.value] = item.open + ',' + item.close;
		}
	}

	for (let item of data.mac_time) {
		if (item.open != '' && item.close != '') {
			obj_ckc[item.value] = item.open + ',' + item.close;
		}
	}

	if (JSON.stringify(obj_machine) != '{}') {
		data.info.on_off_machine = JSON.stringify(obj_machine)
	}

	if (JSON.stringify(obj_ckc) != '{}') {
		data.info.on_off_ckc = JSON.stringify(obj_ckc)
	}

	let obj = []

	for (let item of machine) {
		for (let ime of data.maclist) {
			if (item == ime.value) {
				obj.push({
					m_id: ime.value,
					machine_id: ime.macid,
					machine_name: ime.label,
					on_off_ckc: data.info.on_off_ckc,
					on_off_machine: data.info.on_off_machine,
					status: data.info.status
				})
			}
		}
	}
	data.mtloading = true
	setadd(obj)
}

let setadd = async (e:any) => {
	let m_id = []
	e.forEach(item => {
		m_id.push(item.m_id)
	})
	let parm = {
		m_id: m_id.join(','),
		on_off_ckc: data.info.on_off_ckc,
		on_off_machine: data.info.on_off_machine,
		status: data.info.status
	}
	await addonoff(parm).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.completedAdd'),
				type: 'success'
			})
			data.mtloading = false
			router.back()
			return
		}
		data.mtloading = false
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	}).catch(err => {
		data.mtloading = false
		console.log(err)
	})
}

// 取消
let cancell = () => {
	data.close_time = '22:00'
	data.open_time = '07:00'
	data.cease_time = '22:00'
	data.restore_time = '07:00'
	setinfo()
	router.back()
}

setinfo()

</script>